#include <iostream>
#include <errno.h>
#include <string.h>	//strerror()
#include "ClientSocket.h"
#include "SocketException.h"

using namespace std;

ClientSocket::ClientSocket () : link_status(false), received_all_info(false), m_timer_count(0), m_kep_alive_times(0)
{
	if ( ! Socket::create() )
	{
		throw SocketException ( "Could not create client socket." );
	}
}

bool ClientSocket::conn (std::string host, int port)
{
	if ( ! Socket::connect ( host, port ) )
	{
		cout << host << "/" << port << endl;
		//throw SocketException ( "Could not connect to server." );
	}
	return true;
}

bool ClientSocket::reconn ()
{
	if ( ! Socket::create() )
	{
		throw SocketException ( "Could not create client socket." );
	}
	int status = ::connect ( m_sock, (sockaddr*) &m_addr, sizeof(m_addr) );
	if ( status == 0 )
	{
		return true;
	}
	else
	{
		if (errno)
		{
			throw SocketException (strerror(errno));
		}
		return false;
	}
}

const ClientSocket& ClientSocket::operator << ( const std::string& s ) const
{
	//if ( ! link_status )
	{
		//throw BadConnection ( "Bad connection." );
	}
	if ( ! Socket::send ( s ) )
	{
		throw SocketException ( "Could not write to client socket." );
	}
	return *this;
}

const ClientSocket& ClientSocket::operator >> ( std::string& s ) const
{
	/*
	if ( ! link_status )
	{
		throw BadConnection ( "Bad connection." );
	}
	*/
	if ( ! Socket::recv ( s ) )
	{
		throw SocketException ( "Could not read from client socket." );
	}
	return *this;
}

void ClientSocket::set_connected( bool b )
{
	if ( b )
	{
		link_status = true;
	}
	else
	{
		link_status = false;
	}
}

int ClientSocket::timer_count(const int inst)
{
	switch (inst)
	{
		case SET_ZERO : m_timer_count = 0;break;
		case SELF_INCR: m_timer_count++;  break;
		default       : break;
	}
	return m_timer_count;
}

int ClientSocket::kep_alive_times (const int inst)
{
	switch (inst)
	{
		case SET_ZERO : m_kep_alive_times = 0;break;
		case SELF_INCR: m_kep_alive_times++;  break;
		default       : break;
	}
	return m_kep_alive_times;
}

bool ClientSocket::nonblock_connection_success ()
{
	if (Socket::got_no_error_on_socket())
	{
		return true;
	}
}


